// pages/friends/index.ts
import tran from '../../../utils/language'
import { handleImUserData, debounce } from '../../../utils/index.js'
import { contactBlacklist, presenceList } from '../../../utils/api.js'
// 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _t: tran._t('shieldUserList'),
    _tBase: tran._t('base'),
    navBarHeight: getApp().globalData.navBarHeight,
    token: getApp().globalData.token,
    showEventPopup: false,
    userData: [{
      userId: '324242',
      nickname: 'Benjamin',
      avatarurl: 'https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg',
      status: 1, // 1在线 2忙碌 3离线
      personalityAvatar: '', // 性格的图片地址
      gender: 0
    }],
    allUserData: [{
      userId: '324242',
      nickname: 'Benjamin',
      avatarurl: 'https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg',
      status: 1, // 1在线 2忙碌 3离线
      personalityAvatar: '', // 性格的图片地址
      gender: 0
    }
    ],
    downPopupParams: {
      showDownPopup: false,
      showType: 1 // 0 注册 1 今天想做什么
    },
    keyword: '',
    confirmPopup: {
      showPopup: false,
      topTitle: tran._t('base').topTitleTip,
      midText: tran._t('base').releaseUserTip,
      confirmText: tran._t('base').confirmText,
      closeText: tran._t('base').closeBtnText,
    },
    relieveInfo: {
      userId: ''
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.setData({
      userData: [],
      allUserData: [],
    })
    this.getList()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  // 通过我们的接口，获取用户属性
  getUserStatus (arr: any) {
    const params = {
      userIds: arr || []
    }
    presenceList(params).then((res: any) => {
      res.length > 0 && res.map((item: any) => {
          item.avatarurl = item.avatar
          item.puzzleUrl = item.personalityAvatar
          item.nickname = item.pushName
      })
      this.setData({
        userData: res,
        allUserData: JSON.parse(JSON.stringify(res))
      })
    })
  },
  confirmFn() {
    this.closeFn()
    const that = this
    const { relieveInfo } = this.data
    // 调用 IM 的 API 解除屏蔽，将用户移除黑名单
    wx.conn.removeUserFromBlocklist({
      //可以添加单个用户 ID 或批量添加多个用户 ID 组成的数组。
      name: [relieveInfo.userId],
    });
    setTimeout(() => {
      that.joinBlack(relieveInfo.userId)
    }, 300)
  },
  closeFn() {
    const { confirmPopup } = this.data
    confirmPopup.showPopup = false
    this.setData({
      confirmPopup
    })
  },
  /**
   * 防抖搜索
   */
  keywordChange: debounce(function (e: any) {
    let keyword = e[0].detail
    if (keyword) {
      this.setData({
        keyword: keyword
      }, () => {
        this.keyworkSearch()
      })
    } else {
      this.setData({
        userData: this.data.allUserData
      })
    }
  }, 300),
  keyworkSearch () {
    const { keyword, allUserData } = this.data
    let list: any = []
    allUserData.length > 0 && allUserData.map((item: any) => {
      // 名字搜索，前端模糊查询
      if (item.nickname.indexOf(keyword) != -1) {
        list.push(item)
      }
    })
    this.setData({
      userData: list
    })
  },
  /**
   * 获取用户属性
   * @param arr 
   */
  getUserInfo(arr: any) {
    const userIds: any = []
    arr.length > 0 && arr.map((item: any) => {
      userIds.push(item)
    })
    let userList: any = JSON.parse(JSON.stringify(userIds))
    wx.conn.fetchUserInfoById(arr).then((res: any) => {
      const userInfoList = handleImUserData(userList, res.data)
      this.setData({
        userData: JSON.parse(JSON.stringify(userInfoList)),
        allUserData: JSON.parse(JSON.stringify(userInfoList))
      })
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // this.getList()
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        activeKey: "friends"
      })
    }
  },
  /**
   * 解除屏蔽
   */
  relieveShield(e: any) {
    const info = e.currentTarget.dataset.info
    const {confirmPopup} = this.data
    confirmPopup.showPopup = true
    this.setData({
      relieveInfo: info,
      confirmPopup
    })
    // const that = this
    // wx.showModal({
    //   title: '提示',
    //   content: '确定要将该用户解除屏蔽吗？',
    //   success(res) {
    //     if (res.confirm) {
    //       // 调用 IM 的 API 解除屏蔽，将用户移除黑名单
    //       wx.conn.removeUserFromBlocklist({
    //         //可以添加单个用户 ID 或批量添加多个用户 ID 组成的数组。
    //         name: [info.userId],
    //       });
    //       setTimeout(() => {
    //         that.joinBlack(info.userId)
    //       }, 300)
    //     } else if (res.cancel) {
    //       console.log('用户点击取消')
    //     }
    //   }
    // })
  },
  
  /**
   * 加入黑名单（我们这边的接口，得先调用im的加入黑名单接口后，再调用此接口）
   */
  joinBlack (userId) {
    const params = {
      tagetUserId: userId,
      flag: false, // true加入黑名单 false移除黑名单
    }
    contactBlacklist(params).then((res: any) => {
      this.getList()
    })
  },
  /**
   * 查询黑名单列表
   */
  getList() {
    wx.conn.getBlocklist().then((res: any) => {
      // this.getUserInfo(res.data)
      console.log(res);
      if (res.data.length > 0) {
        this.getUserStatus(res.data)
      } else {
        this.setData({
          userData: [],
          allUserData: []
        })
      }
    });
  },
  closeDownPopup() {
    const downPopup = this.selectComponent('#down-popup');
    const { downPopupParams } = this.data
    downPopupParams.showDownPopup = false
    this.setData({ downPopupParams: downPopupParams })
    downPopup && downPopup.hidePopup()
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onClosePopup() {
    // const customPopup = this.selectComponent('#event-popup');
    // customPopup && customPopup.hidePopup()
    this.setData({
      showEventPopup: false
    })
  },
  moreTap() {
    this.setData({
      showEventPopup: true
    })
  },
  methods: {
  }
})